var debug = require('debug')('stringReverse'),
    stacksServer = require('..'),
    stacksClient = require('..');

stacksServer.listen(3000, function() {
  debug('stacksServer listening');

  stacksClient.connect(3000, function(client) {
    debug('stacksClient connected');

    client.on('string reverse', function(string, reply) {
      debug('client: stringReverse request received');

      var reversedString = string.split("").reverse().join("");
      var error = null;

      if (Date.now() % 2) {
        error = new Error('uh oh');
      }

      // Take three seconds to show concurrency limit
      setTimeout(function() {
        reply(error, reversedString);
      }, 1000);
    }, 15); // handle only 15 concurrent string:reverse requests at a time

    for (var i = 0; i < 100; i++) {
    stacksServer.request('string reverse', 'hello', { maxRetries: 2 }, function (error, reversedString) {
      debug('server: stringReverse request returned');

      if (error) {
        console.error('Failed to reverse string after 2 retries. Error:', error);
      } else {
        console.log('Reversed string:', reversedString); // Reversed string: olleh
      }
    });
  }

  });

});